use "$base_out/2016t1_FullyLinked_mainTE_own.dta", clear

keep $controls2 gradename gradename2 d* academyid formerprovince2 stratascore percentscore_Z *T3ET15* *T1DG16*  treatment pupilid period Subject pupils tutors TTR  DateOfBirth gender gradename AgeFirstBridge treatment academyid2 formerprovince2 stratascore  tutors pupils GradeName2016
gen Age=2016-year(DateOfBirth)



gen Tested=!missing(percentscore_Z)
drop if period<=1
drop if period=="T3ET15":periodl
drop if period=="T1DG16":periodl
compress

keep pupilid period Tested Subject  DateOfBirth gender AgeFirstBridge treatment academyid2 formerprovince2 stratascore  tutors pupils GradeName2016  Male gradename2
greshape wide Tested, i(pupilid period) j(Subject) string

keep if pupils==1

replace Testedmath=0 if Testedmath==.
xtset pupilid period
tsfill, full
xfill GradeName2016 DateOfBirth AgeFirstBridge Male gender gradename2 formerprovince2 stratascore academyid2 treatment, i(pupilid)
replace Testedmath=0 if Testedmath==.
replace TestedEnglish=0 if TestedEnglish==.
replace TestedSwahili=0 if TestedSwahili==.
 
gen term1=(period=="T1MT16":periodl)
gen term2=(period=="T1ET16":periodl)
gen term3=(period=="T2MT16":periodl)
gen term4=(period=="T2ET16":periodl)
gen term5=(period=="T3MT16":periodl)
gen term6=(period=="T3ET16":periodl)


label var term1 T1MT16
label var term2 T1ET16
label var term3 T2MT16
label var term4 T2ET16
label var term5 T3MT16
label var term6 T3ET16

gen Age=2016-year(DateOfBirth)

drop if Age==.


*reghdfe Age c.Testedmath##c.treatment, vce(cluster academyid2) ab(formerprovince2#stratascore)
eststo clear
foreach subject in $Outcomes_core{
    gen Tested=Tested`subject'
	label var Tested "Tested"
			eststo: reghdfe Male c.Tested##c.treatment, vce(cluster academyid2) ab((gradename2#formerprovince2#stratascore)#c.(term*))
			estadd ysumm
			sum Male if Tested==0 & e(sample)==1
			estadd scalar ymean2=r(mean)
			eststo: reghdfe Age c.Tested##c.treatment, vce(cluster academyid2) ab((gradename2#formerprovince2#stratascore)#c.(term*))
			estadd ysumm
			sum Age if Tested`subject'==0 & e(sample)==1
			estadd scalar ymean2=r(mean)	
			drop Tested
}
					
esttab  using "$results/LatexCode/Balance_missing_male_age.tex", se fragment ar2 booktabs label b(a2) se(a2) nocon nonumber ///
		star(* 0.10 ** 0.05 *** 0.01) ///
		replace keep(*treatment* *Tested*) stats(ymean2 N N_clust , labels("Mean not tested" "N. of obs." "Number of schools")) ///
		nonotes 
	